using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace TCClientService
{
  static class TCHttpService
  {
    static readonly System.Text.Json.JsonSerializerOptions _options = new() { IncludeFields = true };
    /// <summary>
    /// 异步发送消息。
    /// </summary>
    /// <param name="client">发送消息的客户端</param>
    /// <param name="request">消息头（Content被覆盖）</param>
    /// <param name="content">消息体</param>
    /// <param name="success">返回成功则调用，传入成功消息体的字符串</param>
    /// <param name="failure">返回失败则调用，传入失败消息体的字符串</param>
    /// <param name="InternetFailure">网络错误则调用</param>
    /// <returns></returns>
    internal static async Task SendAsync<T>(HttpClient client, HttpRequestMessage request, object content, Action<T> success, Action<string> failure, Action InternetFailure)
    {
      request.Content = JsonContent.Create(content, options: _options);
      try
      {
        var response = await client.SendAsync(request);
        var result = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
          if (result != "")
            success(await response.Content.ReadFromJsonAsync<T>());
          else
            success(default);
        }
        else
          failure(await response.Content.ReadAsStringAsync());
      }
      catch (HttpRequestException)
      {
        InternetFailure();
      }
    }
  }
}
